package com.effort.com.effort.excle.pool;

import com.effort.com.effort.excle.core.exception.GlobalException;
import org.influxdb.InfluxDB;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * influxdb 连接池
 */
@Component
public class InfluxDbPool {

    private Map<String, InfluxDB> pool = new HashMap<>();

    /**
     * 将连接注册到连接池之中
     *
     * @param key
     * @param influxDB
     */
    public void register(String key, InfluxDB influxDB) {
        this.pool.put(key, influxDB);
    }

    public InfluxDB getConnectionByKey(String key) {
        InfluxDB influxDB = this.pool.get(key);
        if (Objects.isNull(influxDB)) {
            throw new GlobalException("连接信息出错,请重新连接");
        }
        return influxDB;
    }

    /**
     * 清除连接池之中的内容
     */
    public void clear() {
        pool.values().forEach(InfluxDB::close);
        this.pool.clear();
    }
}
